package com.taomus.mytools.helper.other.pcm;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class WaveHeader {
	public final char fileID[] = { 'R', 'I', 'F', 'F' };
	public int fileLength;
	public char wavTag[] = { 'W', 'A', 'V', 'E' };
	public char fmtHdrID[] = { 'f', 'm', 't', ' ' };
	public int fmtHdrLeth = 16;
	public short formatTag = 0x0001;
	public short channels = 1;
	public short samplesPerSec = 16000;
	public short bitsPerSample = 16;
	public short blockAlign = (short) (channels * bitsPerSample / 8);
	public int avgBytesPerSec = blockAlign * samplesPerSec;
	public char dataHdrID[] = { 'd', 'a', 't', 'a' };
	public int dataHdrLeth;	
	
	public WaveHeader(int pcmSize) {
		super();
		this.fileLength = pcmSize + (44-8);
		this.dataHdrLeth = pcmSize;
	}


	public byte[] getHeader() throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		WriteChar(bos, fileID);
		WriteInt(bos, fileLength);
		WriteChar(bos, wavTag);
		WriteChar(bos, fmtHdrID);
		WriteInt(bos, fmtHdrLeth);
		WriteShort(bos, formatTag);
		WriteShort(bos, channels);
		WriteInt(bos, samplesPerSec);
		WriteInt(bos, avgBytesPerSec);
		WriteShort(bos, blockAlign);
		WriteShort(bos, bitsPerSample);
		WriteChar(bos, dataHdrID);
		WriteInt(bos, dataHdrLeth);
		bos.flush();
		byte[] r = bos.toByteArray();
		bos.close();
		return r;
	}

	public void WriteShort(ByteArrayOutputStream bos, int s) throws IOException {
		byte[] mybyte = new byte[2];
		mybyte[1] = (byte) ((s << 16) >> 24);
		mybyte[0] = (byte) ((s << 24) >> 24);
		bos.write(mybyte);
	}

	public void WriteInt(ByteArrayOutputStream bos, int n) throws IOException {
		byte[] buf = new byte[4];
		buf[3] = (byte) (n >> 24);
		buf[2] = (byte) ((n << 8) >> 24);
		buf[1] = (byte) ((n << 16) >> 24);
		buf[0] = (byte) ((n << 24) >> 24);
		bos.write(buf);
	}

	public void WriteChar(ByteArrayOutputStream bos, char[] id) {
		for (int i = 0; i < id.length; i++) {
			char c = id[i];
			bos.write(c);
		}
	}


}
